<template>
    <div 
        class="home" 
        :style="{background: `url(${useBackgroundImg}) no-repeat 100% 100%`,backgroundSize: 'cover'}"
    >
        <div class="content">
            <RelationGraph 
                ref="seeksRelationGraph" 
                :options="graphOptions" 
                :on-node-click="onNodeClick"
            >
                <template v-slot:node="{ node }">
                    <div style="display: flex;">
                        <div style="flex: 1;">
                            <van-image 
                                style="width: 90%;" 
                                :src="node.data.sex == '男' ? manPng : womanPng"
                                fit="fill"
                            ></van-image>
                            {{ node.data.name }}
                        </div>
                        <div style="flex: 1;">
                            <van-image 
                                v-if="node.data?.mate?.name" 
                                style="width: 90%;" 
                                :src="node.data.mate.sex == '男' ? manPng : womanPng" 
                                fit="fill"
                            ></van-image>
                            <div v-if="node.data?.mate?.name">{{ node.data.mate.name }}</div>
                        </div>
                    </div>
                </template>
            </RelationGraph>
        </div>
        <div class="myicon">
            <div @click="isBackgroundPopupShow = true">
                <van-icon 
                    name="photo-o" 
                    color="rgb(68 185 30)" 
                    size="6vw" 
                />
                <div>背景</div>
            </div>
            <div style="padding-top: 3vw" @click="refresh">
                <van-icon 
                    name="replay" 
                    color="rgb(68 185 30)" 
                    size="6vw" 
                />
                <div>重置</div>
            </div>
            <div 
                style="padding-top: 3vw" 
                @click="$router.push('/pedigreeOfAclan')"
            >
                <van-icon 
                    name="home-o" 
                    color="rgb(68 185 30)" 
                    size="6vw" 
                />
                <div>主页</div>
            </div>
        </div>
        <van-popup 
            v-model:show="isShowNodeMenuPanel" 
            :style="{ width: '90%', height: '30%' }"
        >
            <div style="display: flex;justify-content: space-between;padding: 5%;background-color: rgb(218, 223, 238);">
                <div style="flex: 5;display: flex;align-items: center;">
                    <van-image 
                        style="width: 20%;" 
                        :src="currentNode.data.sex == '男' ? manPng : womanPng" 
                        fit="fill"
                    ></van-image>
                    <div style="padding-left: 5vw;">{{ currentNode.data.name }}</div>
                </div>
                <van-button 
                    type="primary" 
                    style="flex: 1;" @click="$router.push('/createFamilyTree?type=editMe&cm_id=' + currentNode.id + '&cm_mainid=' + $route.query.cm_mainid + '&isdel=' + (graph_json_data1.nodes.length>1 ? 'Y' : 'N') + '&cm_name=' + currentNode.data.name )"
                >
                    编辑
                </van-button>
                <van-button 
                    type="primary" 
                    style="flex: 1;" 
                    @click="myrelation(currentNode.id, currentNode.data.fatherid)"
                >
                    关系
                </van-button>
            </div>
            <div style="padding: 5%;text-align: left;">添加亲人</div>
            <div style="padding-left: 5%;text-align: left;">
                <van-button v-if="!currentNode.data.fatherid" type="primary" style="margin-right: 1vw;" @click="$router.push('/createFamilyTree?type=editFather&cm_id=' + currentNode.id +'&cm_mainid=' + $route.query.cm_mainid + '&cm_name=父亲')">父亲</van-button>
                <van-button 
                    type="primary" 
                    style="margin-right: 1vw;" @click="$router.push('/createFamilyTree?type=editMate&cm_spouseid=' + currentNode.data.mate.id + '&cm_id=' + currentNode.id + '&cm_mainid=' + $route.query.cm_mainid + '&cm_name=配偶')"
                >
                    配偶
                </van-button>
                <van-button 
                    type="primary" 
                    style="margin-right: 1vw;" @click="$router.push('/createFamilyTree?type=editChildren&cm_fatherid=' + currentNode.id + '&cm_motherid=' + currentNode.data.mate.id + '&cm_mainid=' + $route.query.cm_mainid + '&cm_name=子女')"
                >
                    子女
                </van-button>
            </div>
        </van-popup>

        <van-popup 
            v-model:show="isBackgroundPopupShow" 
            :style="{ width: '90%', height: '40%' }"
        >
            <div class="backg">
                <van-image 
                    v-for="(item, index) in backgroundImgArr" 
                    :key="index" 
                    width="22vw" 
                    height="50vw" 
                    :src="item" 
                    fit="fill" 
                    @click="imgChange(item)"
                ></van-image>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
    // 如果您没有在main.js文件中使用Vue.use(RelationGraph); 就需要使用下面这一行代码来引入relation-graph
    import RelationGraph from 'relation-graph/vue3'
    import { getClanMemberByIdApi, updateImgApi } from '@/apis'
    import { showDialog, showConfirmDialog, showLoadingToast, closeToast, showSuccessToast, showFailToast, showToast } from 'vant'
    import { markRaw, reactive, ref, toRaw, onMounted, onBeforeMount, readonly, onBeforeUnmount } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const route = useRoute()
    const router = useRouter()
    const manPng = ref(new URL('@/assets/relativeGraph/man.png', import.meta.url).href)
    const womanPng = ref(new URL('@/assets/relativeGraph/woman.png', import.meta.url).href)

    const useBackgroundImg: Ref<string> = ref('/business/image/lygzp/202310101.png')
    const backgroundImgArr: Ref<any[]> = ref(['/business/image/lygzp/202310101.png', '/business/image/lygzp/202310102.jpg', '/business/image/lygzp/202310103.jpg'])
    const isBackgroundPopupShow: Ref<boolean> = ref(false)
    const ranking: Ref<any[]> = ref(['长', '次', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十'])
    const graphOptions: Ref<any> = ref({
        "disableDragNode": true, //是否禁用图谱中节点的拖动
        "defaultFocusRootNode": false,
        "disableLineClickEffect": true,
        "allowShowMiniToolBar": false, //显示工具栏
        "allowSwitchLineShape": false, //是否在工具栏中显示切换线条形状的按钮
        "allowAutoLayoutIfSupport": false, //是否在工具栏中显示【自动布局】按钮（只有在布局支持且此选项为true时才会显示的按钮）
        "allowShowDownloadButton": false, //是否在工具栏中显示【下载图片】按钮
        "allowShowZoomMenu": false, //是否在右侧菜单栏显示放大缩小的按钮，此设置和disableZoom不冲突
        "defaultNodeColor": "rgb(241 191 191)", //默认节点颜色
        "defaultNodeBorderColor": "rgb(175 209 175)", //默认节点边框颜色
        "defaultNodeFontColor": "rgba(81, 75, 75, 1)", //默认节点文字颜色
        "defaultLineShape": 1, //默认的线条样式（1:直线/2:样式2/3:样式3/4:折线/5:样式5/6:样式6）
        "defaultNodeShape": 1, //默认的节点形状，0:圆形；1:矩形
        "defaultNodeWidth": "120", //默认的节点宽度
        "defaultNodeHeight": "80", //默认的节点高度
        "defaultJunctionPoint": "tb", //默认的连线与节点接触的方式（border:边缘/ltrb:上下左右/tb:上下/lr:左右）当布局为树状布局时应使用tb或者lr，这样才会好看
        "defaultLineColor": "rgb(32,35,35)", //当线条被选中时的颜色
        "layouts": [
            {
                "label": "中心",
                "layoutName": "tree",
                "layoutClassName": "seeks-layout-center",
                'min_per_width': 1000,
                'min_per_height': 200,
                // levelDistance: '150'

            }
        ],
        "defaultLineMarker": {
            "markerWidth": "",
            "markerHeight": "",
            "refX": "",
            "refY": "",
            "data": ""
        },
    })
    const currentNode: Ref<any> = ref({
        data: {
            name: '',
            sex: ''
        }
    })
    const isShowNodeMenuPanel: Ref<boolean> = ref(false)
    const graph_json_data1: Ref<any> = ref({
         // rootId: 'a',
         rootId: '',
        nodes: [
            // { 'id': 'a', 'text': '', 'data': { 'name': '一代', 'sex': '男', 'mate': { 'id': 'aa', 'name': '一代老婆', 'sex': '女', } } },
            // { 'id': 'b', 'text': '', 'data': { 'name': '二代', 'sex': '男', 'mate': { 'id': 'bb', 'name': '二代老婆', 'sex': '女', } } },
            // { 'id': 'b1', 'text': '', 'data': { 'name': '三代', 'sex': '男', 'mate': { 'id': 'b1b1', 'name': '三代老婆', 'sex': '女', } } },
            // { 'id': 'b1-1', 'text': '', 'data': { 'name': '四代', 'sex': '男', 'mate': { 'id': 'b1-1b1-1', 'name': '张四代老婆', 'sex': '女', } } },
            // { 'id': 'b2', 'text': '', 'data': { 'name': '三代2', 'sex': '男', 'mate': { 'id': 'b2b2', 'name': '三代2老婆', 'sex': '女', } } },
            // { 'id': 'c', 'text': '', 'data': { 'name': '二代2', 'sex': '男', 'mate': { 'id': 'cc', 'name': '二代2老婆', 'sex': '女', } } },
        ],
        lines: [
            // { 'from': 'a', 'to': 'b' },
            // { 'from': 'b', 'to': 'b1' },
            // { 'from': 'b1', 'to': 'b1-1' },
            // { 'from': 'b', 'to': 'b2' },
            // { 'from': 'a', 'to': 'c' },
        ]
    })
    const graph_json_data2: Ref<any> = ref({
        // rootId: 'a',
        rootId: '',
        nodes: [
            
        ],
        lines: [
            
        ]
    })
    onMounted(() => {
        showSeeksGraph();
    })

    const seeksRelationGraph = ref<RelationGraph>()
    const refresh = () => {
        seeksRelationGraph.value.setJsonData(graph_json_data1.value, (graphInstance) => {
            // 这些写上当图谱初始化完成后需要执行的代码
            // 用后台数据显示会不正常，要重新执行
            // seeksRelationGraph.value.refresh()
        });
    }
    const myrelation = (id, fid) => {
        if (id && fid) {
            graph_json_data2.value.lines = []
            graph_json_data2.value.nodes = []
            let fatherid = ''
            graph_json_data1.value.nodes.forEach((item1, index1) => {
                if (id == item1.id && item1.data.fatherid) {
                    fatherid = item1.data.fatherid
                    graph_json_data1.value.nodes.forEach((item2, index2) => {
                        if (fatherid == item2.id && item2.data.fatherid) {
                            fatherid = item2.data.fatherid
                        }
                    })
                }
            })
            graph_json_data2.value.rootId = fatherid
            // let peoplearr = [fatherid]
            let fun = (val) => {
                console.log(graph_json_data1.value)
                graph_json_data1.value.nodes.forEach((item1, index1) => {
                    if (val == item1.data.fatherid) {
                        // peoplearr.push(item1.id)
                        graph_json_data2.value.lines.push({
                            from: val,
                            to: item1.id,
                            sex: item1.data.sex, //不会显示，给下面循环用的
                            // text: ranking.value[Number(item1.data.familyrow)-1] + (item1.data.sex == '男' ? '子' : '女') //显示在连接线上的内容
                            text: '',
                            lineShape: 2, //线条样式
                        })
                        fun(item1.id)
                    }
                    if (val == item1.id) {
                        graph_json_data2.value.nodes.push(item1)
                    }
                })
            }
            fun(fatherid)
                // 循环判断长子长女给排名
                let fidArr = []
            for(let i = 0; i < graph_json_data2.value.lines.length; i++) {
                if (!graph_json_data2.value.lines[i].from) {
                    continue
                }
                // 如果包含相同的父id则已经循环过不用再判断了
                if(fidArr.includes(graph_json_data2.value.lines[i].from)) {
                    continue
                } else {
                    fidArr.push(graph_json_data2.value.lines[i].from)
                }
                let manRank = 0
                let womanRank = 0
                console.log(graph_json_data1.value.nodes)

                if (graph_json_data2.value.lines[i].sex == '男') {
                    graph_json_data2.value.lines[i].text = ranking.value[manRank] + '子'
                    manRank++
                } else if (graph_json_data2.value.lines[i].sex == '女') {
                    graph_json_data2.value.lines[i].text = ranking.value[womanRank] + '女'
                    womanRank++
                }
                for(let j = i + 1; j < graph_json_data2.value.lines.length; j++) {
                    if (graph_json_data2.value.lines[i].from != graph_json_data2.value.lines[j].from) {
                        continue
                    } else {
                        if (graph_json_data2.value.lines[j].sex == '男') {
                            graph_json_data2.value.lines[j].text = ranking.value[manRank] + '子'
                            manRank++
                        } else if (graph_json_data2.value.lines[j].sex == '女') {
                            graph_json_data2.value.lines[j].text = ranking.value[womanRank] + '女'
                            womanRank++
                        }
                    }
                }
            }


            seeksRelationGraph.value.setJsonData(graph_json_data2.value, (graphInstance) => {
                // 这些写上当图谱初始化完成后需要执行的代码
                // 用后台数据显示会不正常，要重新执行
                // seeksRelationGraph.value.refresh()
            });
        }
        isShowNodeMenuPanel.value = false
    }
    const showSeeksGraph = () => {
        let nodes = []
        let lines = []
        getClanMemberByIdApi({
            company: '连云港人文纪念园智慧陵园管理系统',
            dw: '连云港人文纪念园',
            sId: route.query.cm_mainid
        }).then(res => {
            console.log(res.cm_img[0].cm_img)   
            if(res.cm_img[0].cm_img) {
                useBackgroundImg.value = res.cm_img[0].cm_img
            }
            let arr = JSON.parse(JSON.stringify(res.data))
            console.log(arr)
            for(let i = 0; i < arr.length; i++) {
                let min = i // 暂定i为最小
                console.log('第一个循环语句---'+ i)
                for(let j = i + 1; j < arr.length; j++) {
                    console.log('第二个循环语句---'+ j)
                    if (Number(arr[min].cm_familyrow) > Number(arr[j].cm_familyrow)) { // 找到最小的
                        min = j
                    }
                }
                [arr[i], arr[min]] = [arr[min], arr[i]] // 内循环结束交换
            }
            console.log(arr)

            arr.forEach((item, index) => {
                nodes.push({
                    id: item.cm_id,
                    data: {
                        name: item.cm_name,
                        sex: item.cm_sex,
                        mate: {
                            id: item.cmid, //cm_spouseid
                            name: item.name,
                            sex: item.sex
                        },
                        fatherid: item.cm_fatherid,
                        familyrow: item.cm_familyrow
                    },

                })
                if (item.cm_fatherid) {
                    lines.push({
                        from: item.cm_fatherid,
                        to: item.cm_id,
                        sex: item.cm_sex, //不会显示，给下面循环用的
                        // text: ranking.value[Number(item.cm_familyrow)-1] + (item.cm_sex == '男' ? '子' : '女'), //显示在连接线上的内容
                        text: '',
                        lineShape: 4, //线条样式
                    })
                } else {
                    graph_json_data1.value.rootId = item.cm_id
                }
            })
            // 循环判断长子长女给排名
            let fidArr = []
            for(let i = 0; i < lines.length; i++) {
                if (!lines[i].from) {
                    continue
                }
                // 如果包含相同的父id则已经循环过不用再判断了
                if(fidArr.includes(lines[i].from)) {
                    continue
                } else {
                    fidArr.push(lines[i].from)
                }
                let manRank = 0
                let womanRank = 0

                if (lines[i].sex == '男') {
                    lines[i].text = ranking.value[manRank] + '子'
                    manRank++
                } else if (lines[i].sex == '女') {
                    lines[i].text = ranking.value[womanRank] + '女'
                    womanRank++
                }
                for(let j = i + 1; j < lines.length; j++) {
                    if (lines[i].from != lines[j].from) {
                        continue
                    } else {
                        if (lines[j].sex == '男') {
                            lines[j].text = ranking.value[manRank] + '子'
                            manRank++
                        } else if (lines[j].sex == '女') {
                            lines[j].text = ranking.value[womanRank] + '女'
                            womanRank++
                        }
                    }

                }
            }
            graph_json_data1.value.nodes.push(...nodes)
            graph_json_data1.value.lines.push(...lines)
            seeksRelationGraph.value.setJsonData(graph_json_data1.value, (graphInstance) => {
                // 这些写上当图谱初始化完成后需要执行的代码
                // 用后台数据显示会不正常，要重新执行
                // seeksRelationGraph.value.refresh()
            });
        })
    }
    const onNodeClick = (nodeObject, $event) => {
        currentNode.value = nodeObject;
        isShowNodeMenuPanel.value = true;
        console.log('onNodeClick:', nodeObject);
        console.info('onNodeClick:', graph_json_data1.value)
        console.info('onNodeClick:', graph_json_data2.value)
    }
    const imgChange = (val) => {
        useBackgroundImg.value = val
        isBackgroundPopupShow.value = false
        updateImgApi({
            sId: route.query.cm_mainid,
            img: val
        })
    }
</script>

<style lang="scss" scoped>
.home {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}
// .home::before {
//     content: '';
//     position: absolute;
//     top: 0;
//     right: 0;
//     bottom: 0;
//     left: 0;
//     filter: blur(3px);
//     background: url('@/assets/bg/bg6.png') no-repeat 100% 100%;
//     background-size: cover;
//     z-index: -1;
// }
:deep(.rel-map) {
    background: rgba(255,255,255,0.8) !important;
}
.content {
    flex: 1;
    overflow: auto;
}
.myicon {
    position: absolute;
    right: 20px;
    bottom: 20px;
    font-size: 12px;
    z-index: 10;
}

:deep(.c-rg-line-text) {
    font-size: 18px;
    transform: rotate(-90deg) translate(10px, 30px);
}
.backg {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
}
</style>